<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\StorePlatform;
use App\Models\YhMerchantSupplier;
use App\Models\Store;
use App\Models\PickupPointVendor;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SupplierController extends Controller
{
    /**
     * 供应商清单
     *
     * @param Content $content
     * @param Request $request
     * @return Content
     */
    public function index(Content $content, Request $request)
    {
        return $content
            ->title('供应商清单')
            ->description('管理供应商信息')
            ->body($this->renderSupplierList($request));
    }

    /**
     * 供应商详情
     *
     * @param Content $content
     * @param int $id
     * @return Content
     */
    public function show(Content $content, $id)
    {
        return $content
            ->title('供应商详情')
            ->description('查看供应商详细信息')
            ->body($this->renderSupplierDetail($id));
    }

    /**
     * 渲染供应商列表
     *
     * @param Request $request
     * @return string
     */
    // public function renderSupplierList_old(Request $request)
    // {
    //     try {
    //         // 获取平台列表（带统计）- 使用直接数据库查询避免内存问题
    //         $platformsData = DB::select('
    //             SELECT p.id, p.platformname, p.platformcode, p.applyname, p.authorizationlimit,
    //                    COUNT(v.id) as vendor_count, COUNT(s.id) as store_count
    //             FROM ims_yz_store_platform p 
    //             LEFT JOIN ims_yz_vendor v ON p.id = v.platform_id AND v.status = 1
    //             LEFT JOIN ims_yz_store s ON p.id = s.platform_id
    //             WHERE p.status = 1 
    //             GROUP BY p.id, p.platformname, p.platformcode, p.applyname, p.authorizationlimit
    //             ORDER BY p.id ASC
    //         ');
            
    //         $colors = ['primary', 'success', 'info', 'warning', 'secondary'];
    //         $platforms = [];
            
    //         foreach ($platformsData as $platform) {
    //             $color = $colors[$platform->id % count($colors)];
                
    //             // 获取该平台下当前门店已分配的供应商数量
    //             $storeId = $request->get('store_id', 1);
    //             $assignedCount = DB::selectOne('
    //                 SELECT COUNT(*) as count 
    //                 FROM ims_yz_pickup_point_vendors ppv
    //                 INNER JOIN ims_yz_vendor v ON ppv.vendor_id = v.id
    //                 WHERE ppv.store_id = ? AND v.platform_id = ? AND v.status = 1
    //             ', [$storeId, $platform->id])->count ?? 0;
                
    //             $platforms[] = [
    //                 'id' => $platform->id,
    //                 'name' => $platform->platformname,
    //                 'code' => $platform->platformcode,
    //                 'color' => $color,
    //                 'vendor_count' => $platform->vendor_count,
    //                 'store_count' => $platform->store_count,
    //                 'assigned_count' => $assignedCount,
    //                 'active' => $request->get('platform_id') == $platform->id,
    //                 'count' => $platform->vendor_count
    //             ];
    //         }
            
    //         // 如果没有选择平台，默认选择第一个
    //         if (!$request->has('platform_id') && !empty($platforms)) {
    //             $platforms[0]['active'] = true;
    //             $selectedPlatformId = $platforms[0]['id'];
    //         } else {
    //             $selectedPlatformId = $request->get('platform_id');
    //         }

    //         // 当前选中门店信息（从URL参数或默认值获取）
    //         $storeId = $request->get('store_id', 1);
    //         $selectedStore = Store::find($storeId);
    //         $selectedStoreData = [
    //             'id' => $selectedStore->id ?? 1,
    //             'name' => $selectedStore->store_name ?? '默认门店'
    //         ];

    //         // 获取供应商数据 - 使用直接数据库查询
    //         $suppliersQuery = "
    //             SELECT v.id, v.supplier_name, v.mobile, v.real_name, v.applicant_id, v.platform_id, p.platformname
    //             FROM ims_yz_vendor v
    //             LEFT JOIN ims_yz_store_platform p ON v.platform_id = p.id
    //             WHERE v.status = 1
    //         ";
            
    //         $params = [];
            
    //         if ($selectedPlatformId) {
    //             $suppliersQuery .= " AND v.platform_id = ?";
    //             $params[] = $selectedPlatformId;
    //         }
            
    //         if ($request->filled('supplier_name')) {
    //             $suppliersQuery .= " AND v.supplier_name LIKE ?";
    //             $params[] = '%' . $request->supplier_name . '%';
    //         }
            
    //         $suppliersQuery .= " ORDER BY v.supplier_name ASC";
            
    //         $suppliersData = DB::select($suppliersQuery, $params);
            
    //         // 获取当前门店已分配的供应商ID列表
    //         $assignedVendorIds = PickupPointVendor::getVendorIdsByStore($selectedStoreData['id']);

    //         $suppliers = [];
    //         foreach ($suppliersData as $vendor) {
    //             $suppliers[] = [
    //                 'id' => $vendor->id,
    //                 'name' => $vendor->supplier_name,
    //                 'supplier' => [
    //                     'name' => $vendor->real_name ?: '未设置',
    //                     'id' => $vendor->applicant_id,
    //                     'avatar' => $this->generateVendorAvatar($vendor->supplier_name)
    //                 ],
    //                 'phone' => $vendor->mobile ?: '未设置',
    //                 'platform' => $vendor->platformname ?: '未分配',
    //                 'assigned' => in_array($vendor->id, $assignedVendorIds)
    //             ];
    //         }

    //         return view('admin.supplier.index', compact('platforms', 'selectedStoreData', 'suppliers'));
    //     } catch (\Exception $e) {
    //         // 如果数据库查询失败，返回默认数据
    //         return $this->renderDefaultSupplierList();
    //     }
    // }

    /**
     * 渲染供应商列表
     *
     * @param Request $request
     * @return string
     */
    public function renderSupplierList(Request $request)
    {
        try {
            // 获取平台列表（带统计）- 使用直接数据库查询避免内存问题
            $merchantsData = DB::select('
            SELECT
            p.id,
            p.name,
            p.code,
            COUNT( v.id ) AS vendor_count,
            COUNT( s.id ) AS store_count 
        FROM
            ims_yh_merchant p
            LEFT JOIN ims_yh_merchant_supplier v ON p.id = v.merchant_id 
            AND v.STATUS = 1
            LEFT JOIN ims_yz_store s ON p.id = s.merchant_id 
        WHERE
            p.STATUS = 1 
        GROUP BY
            p.id,
            p.name,
            p.code
        ORDER BY
            p.id ASC
            ');
            
            $colors = ['primary', 'success', 'info', 'warning', 'secondary'];
            $merchants = [];
            
            foreach ($merchantsData as $merchant) {
                $color = $colors[$merchant->id % count($colors)];
                
                // 获取该平台下当前门店已分配的供应商数量
                $storeId = $request->get('store_id', 1);
                $assignedCount = DB::selectOne('
                    SELECT COUNT(*) as count 
                    FROM ims_yz_pickup_point_vendors ppv
                    INNER JOIN ims_yh_merchant_supplier v ON ppv.vendor_id = v.id
                    WHERE ppv.store_id = ? AND v.merchant_id = ? AND v.status = 1
                ', [$storeId, $merchant->id])->count ?? 0;
                
                $merchants[] = [
                    'id' => $merchant->id,
                    'name' => $merchant->name,
                    'code' => $merchant->code,
                    'color' => $color,
                    'vendor_count' => $merchant->vendor_count,
                    'store_count' => $merchant->store_count,
                    'assigned_count' => $assignedCount,
                    'active' => $request->get('merchant_id') == $merchant->id,
                    'count' => $merchant->vendor_count
                ];
            }
            
            // 如果没有选择平台，默认选择第一个
            if (!$request->has('platform_id') && !empty($merchants)) {
                $merchants[0]['active'] = true;
                $selectedPlatformId = $merchants[0]['id'];
            } else {
                $selectedPlatformId = $request->get('platform_id');
            }

            // 当前选中门店信息（从URL参数或默认值获取）
            $storeId = $request->get('store_id', 1);
            $selectedStore = Store::find($storeId);
            $selectedStoreData = [
                'id' => $selectedStore->id ?? 1,
                'name' => $selectedStore->store_name ?? '默认门店'
            ];

            // 获取供应商数据 - 使用直接数据库查询
            $suppliersQuery = "
                SELECT v.id, v.name, v.applicant_phone, v.applicant_name, v.applicant_uid, v.merchant_id, p.name as merchant_name
                FROM ims_yh_merchant_supplier v
                LEFT JOIN ims_yh_merchant p ON v.merchant_id = p.id
                WHERE v.status = 1
            ";
            
            $params = [];
            
            if ($selectedPlatformId) {
                $suppliersQuery .= " AND v.merchant_id = ?";
                $params[] = $selectedPlatformId;
            }
            
            if ($request->filled('name')) {
                $suppliersQuery .= " AND v.name LIKE ?";
                $params[] = '%' . $request->supplier_name . '%';
            }
            
            $suppliersQuery .= " ORDER BY v.name ASC";
            
            $suppliersData = DB::select($suppliersQuery, $params);
            
            // 获取当前门店已分配的供应商ID列表
            $assignedVendorIds = PickupPointVendor::getVendorIdsByStore($selectedStoreData['id']);

            $suppliers = [];
            foreach ($suppliersData as $vendor) {
                $suppliers[] = [
                    'id' => $vendor->id,
                    'name' => $vendor->name,
                    'supplier' => [
                        'name' => $vendor->applicant_name ?: '未设置',
                        'id' => $vendor->applicant_uid,
                        'avatar' => $this->generateVendorAvatar($vendor->name)
                    ],
                    'phone' => $vendor->applicant_phone ?: '未设置',
                    'merchant' => $vendor->name ?: '未分配',
                    'assigned' => in_array($vendor->id, $assignedVendorIds)
                ];
            }

            return view('admin.supplier.index', compact('merchants', 'selectedStoreData', 'suppliers'));
        } catch (\Exception $e) {
            // 如果数据库查询失败，返回默认数据
            return $this->renderDefaultSupplierList();
        }
    }

    /**
     * 渲染供应商详情
     *
     * @param int $id
     * @return string
     */
    protected function renderSupplierDetail($id)
    {
        $supplier = [
            'id' => $id,
            'name' => '红姐',
            'supplier_info' => [
                'name' => '紫罗兰',
                'id' => 2522,
                'avatar' => ''
            ],
            'phone' => '13811111234',
            'platform' => '抽奖易兑',
            'status' => '正常',
            'created_at' => '2024-01-15 10:30:00'
        ];

        return view('admin.supplier.detail', compact('supplier'));
    }

    

    /**
     * 获取平台列表接口
     *
     * @return JsonResponse
     */
    public function getPlatforms(): JsonResponse
    {
        try {
            // 使用直接数据库查询避免内存问题
            $platformsData = DB::select('
                SELECT p.id, p.platformname, p.platformcode, p.applyname, p.authorizationlimit,
                       COUNT(v.id) as vendor_count, COUNT(s.id) as store_count
                FROM ims_yz_store_platform p 
                LEFT JOIN ims_yz_vendor v ON p.id = v.platform_id AND v.status = 1
                LEFT JOIN ims_yz_store s ON p.id = s.platform_id
                WHERE p.status = 1 
                GROUP BY p.id, p.platformname, p.platformcode, p.applyname, p.authorizationlimit
                ORDER BY p.id ASC
            ');
            
            $colors = ['primary', 'success', 'info', 'warning', 'secondary'];
            $platforms = [];
            
            foreach ($platformsData as $platform) {
                $color = $colors[$platform->id % count($colors)];
                
                // 由于这是API接口，暂时将assigned_count设为0，实际使用时需要传入store_id
                $assignedCount = 0;
                
                $platforms[] = [
                    'id' => $platform->id,
                    'name' => $platform->platformname,
                    'code' => $platform->platformcode,
                    'color' => $color,
                    'vendor_count' => $platform->vendor_count,
                    'store_count' => $platform->store_count,
                    'assigned_count' => $assignedCount
                ];
            }
            
            return response()->json([
                'status' => 'success',
                'data' => $platforms
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取平台列表失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 根据平台ID获取供应商列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getSuppliersByPlatform(Request $request): JsonResponse
    {
        try {
            $platformId = $request->get('platform_id');
            $supplierName = $request->get('supplier_name');
            $storeId = $request->get('store_id', 1); // 从请求中获取store_id，默认为1
            
            // 使用直接数据库查询
            $suppliersQuery = "
                SELECT v.id, v.supplier_name, v.mobile, v.real_name, v.applicant_id, v.platform_id, p.platformname
                FROM ims_yz_vendor v
                LEFT JOIN ims_yz_store_platform p ON v.platform_id = p.id
                WHERE v.status = 1
            ";
            
            $params = [];
            
            if ($platformId) {
                $suppliersQuery .= " AND v.platform_id = ?";
                $params[] = $platformId;
            }
            
            if ($supplierName) {
                $suppliersQuery .= " AND v.supplier_name LIKE ?";
                $params[] = '%' . $supplierName . '%';
            }
            
            $suppliersQuery .= " ORDER BY v.supplier_name ASC";
            
            $suppliersData = DB::select($suppliersQuery, $params);
            
            // 获取当前门店已分配的供应商ID列表
            $assignedVendorIds = PickupPointVendor::getVendorIdsByStore($storeId);

            $suppliers = [];
            foreach ($suppliersData as $vendor) {
                $suppliers[] = [
                    'id' => $vendor->id,
                    'name' => $vendor->supplier_name,
                    'supplier' => [
                        'name' => $vendor->real_name ?: '未设置',
                        'id' => $vendor->applicant_id,
                        'avatar' => $this->generateVendorAvatar($vendor->supplier_name)
                    ],
                    'phone' => $vendor->mobile ?: '未设置',
                    'platform' => $vendor->platformname ?: '未分配',
                    'assigned' => in_array($vendor->id, $assignedVendorIds)
                ];
            }

            return response()->json([
                'status' => 'success',
                'data' => $suppliers
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取供应商列表失败：' . $e->getMessage()
            ], 500);
        }
    }

     /**
     * 根据平台ID获取供应商列表
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function getSuppliersByMerchant(Request $request): JsonResponse
    {
        try {
            $merchant_id = $request->get('merchant_id');
            $supplierName = $request->get('supplier_name');
            $storeId = $request->get('store_id', 1); // 从请求中获取store_id，默认为1
            
            // 使用直接数据库查询
            $suppliersQuery = "
                SELECT v.id, v.name, v.applicant_phone, v.applicant_name, v.applicant_uid, v.merchant_id, p.name as merchant_name
                FROM ims_yh_merchant_supplier v
                LEFT JOIN ims_yh_merchant p ON v.merchant_id = p.id
                WHERE v.status = 1
            ";
            
            $params = [];
            
            if ($merchant_id) {
                $suppliersQuery .= " AND v.merchant_id = ?";
                $params[] = $merchant_id;
            }
            
            if ($supplierName) {
                $suppliersQuery .= " AND v.name LIKE ?";
                $params[] = '%' . $supplierName . '%';
            }
            
            $suppliersQuery .= " ORDER BY v.name ASC";
            
            $suppliersData = DB::select($suppliersQuery, $params);
            
            // 获取当前门店已分配的供应商ID列表
            $assignedVendorIds = PickupPointVendor::getVendorIdsByStore($storeId);

            $suppliers = [];
            foreach ($suppliersData as $vendor) {
                $suppliers[] = [
                    'id' => $vendor->id,
                    'name' => $vendor->name,
                    'supplier' => [
                        'name' => $vendor->applicant_name ?: '未设置',
                        'id' => $vendor->applicant_uid,
                        'avatar' => $this->generateVendorAvatar($vendor->name)
                    ],
                    'phone' => $vendor->applicant_phone ?: '未设置',
                    'merchant' => $vendor->name ?: '未分配',
                    'assigned' => in_array($vendor->id, $assignedVendorIds)
                ];
            }

            return response()->json([
                'status' => 'success',
                'data' => $suppliers
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取供应商列表失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量分配供应商
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function batchAssign(Request $request): JsonResponse
    {
        try {
            $vendorIds = $request->get('vendor_ids', []);
            $storeId = $request->get('store_id');
            $merchant_id = $request->get('merchant_id');
            
            if (!$storeId) {
                return response()->json([
                    'status' => 'error',
                    'message' => '门店ID不能为空'
                ], 400);
            }
            
            if (!$merchant_id) {
                return response()->json([
                    'status' => 'error',
                    'message' => '机构ID不能为空'
                ], 400);
            }
            
            // 验证门店是否存在
            $store = Store::find($storeId);
            if (!$store) {
                return response()->json([
                    'status' => 'error',
                    'message' => '门店不存在'
                ], 404);
            }
            
            // 开始事务处理
            DB::beginTransaction();
            
            try {
                // 第一步：硬删除该门店在指定平台下的现有供应商分配（不使用软删除）
                $recordsToDelete = PickupPointVendor::where('store_id', $storeId)
                    ->whereIn('vendor_id', function($query) use ($merchant_id) {
                        $query->select('id')
                              ->from('ims_yh_merchant_supplier')
                              ->where('merchant_id', $merchant_id)
                              ->where('status', 1);
                    })
                    ->get();
                
                $deletedCount = 0;
                foreach ($recordsToDelete as $record) {
                    $record->forceDelete(); // 使用硬删除
                    $deletedCount++;
                }
                
                $assignedCount = 0;
                
                // 第二步：如果有新的供应商ID，则添加新的分配
                if (!empty($vendorIds)) {
                    // 验证供应商是否存在且有效，并且属于指定平台
                    $validVendorIds = YhMerchantSupplier::withoutGlobalScopes()
                        ->whereIn('id', $vendorIds)
                        ->where('merchant_id', $merchant_id)
                        ->where('status', 1)
                        ->pluck('id')
                        ->toArray();
                    
                    // 添加调试信息
                    \Illuminate\Support\Facades\Log::info('供应商验证详情', [
                        'requested_ids' => $vendorIds,
                        'valid_ids' => $validVendorIds,
                        'vendor_query' => YhMerchantSupplier::whereIn('id', $vendorIds)->toSql(),
                        'vendor_bindings' => YhMerchantSupplier::whereIn('id', $vendorIds)->getBindings()
                    ]);
                    
                    // 添加调试信息
                    \Illuminate\Support\Facades\Log::info('批量分配调试', [
                        'requested_vendor_ids' => $vendorIds,
                        'valid_vendor_ids' => $validVendorIds,
                        'store_id' => $storeId,
                        'merchant_id' => $merchant_id
                    ]);
                    
                    if (!empty($validVendorIds)) {
                        // 批量创建新的分配记录
                        foreach ($validVendorIds as $vendorId) {
                            try {
                                $newAssignment = PickupPointVendor::create([
                                    'store_id' => $storeId,
                                    'vendor_id' => $vendorId
                                ]);
                                $assignedCount++;
                                \Illuminate\Support\Facades\Log::info("成功创建分配记录", ['id' => $newAssignment->id, 'store_id' => $storeId, 'vendor_id' => $vendorId]);
                            } catch (\Exception $e) {
                                \Illuminate\Support\Facades\Log::error("创建分配记录失败", [
                                    'store_id' => $storeId,
                                    'vendor_id' => $vendorId,
                                    'error' => $e->getMessage()
                                ]);
                                throw $e;
                            }
                        }
                    } else {
                        \Illuminate\Support\Facades\Log::warning('没有找到有效的供应商', [
                            'requested_ids' => $vendorIds,
                            'store_id' => $storeId,
                            'merchant_id' => $merchant_id
                        ]);
                    }
                }
                
                // 提交事务
                DB::commit();
                
                return response()->json([
                    'status' => 'success',
                    'message' => "成功保存当前平台分配：删除 {$deletedCount} 个，新增 {$assignedCount} 个供应商",
                    'data' => [
                        'deleted_count' => $deletedCount,
                        'assigned_count' => $assignedCount,
                        'store_id' => $storeId,
                        'merchant_id' => $merchant_id,
                        'total_requested' => count($vendorIds),
                        'valid_vendor_ids' => $validVendorIds ?? [],
                        'debug_info' => [
                            'requested_count' => count($vendorIds),
                            'valid_count' => count($validVendorIds ?? []),
                            'store_exists' => $store ? true : false
                        ]
                    ]
                ]);
                
            } catch (\Exception $e) {
                // 回滚事务
                DB::rollback();
                \Illuminate\Support\Facades\Log::error('批量分配事务失败', [
                    'store_id' => $storeId,
                    'merchant_id' => $merchant_id,
                    'vendor_ids' => $vendorIds,
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
                throw $e;
            }
            
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '保存分配失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量移除供应商
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function batchRemove(Request $request): JsonResponse
    {
        try {
            $vendorIds = $request->get('vendor_ids', []);
            $storeId = $request->get('store_id');
            
            if (empty($vendorIds) || !$storeId) {
                return response()->json([
                    'status' => 'error',
                    'message' => '参数不完整'
                ], 400);
            }
            
            // 验证门店是否存在
            $store = Store::find($storeId);
            if (!$store) {
                return response()->json([
                    'status' => 'error',
                    'message' => '门店不存在'
                ], 404);
            }
            
            // 批量硬删除分配记录（不使用软删除）
            $recordsToRemove = PickupPointVendor::where('store_id', $storeId)
                ->whereIn('vendor_id', $vendorIds)
                ->get();
            
            $removedCount = 0;
            foreach ($recordsToRemove as $record) {
                $record->forceDelete(); // 使用硬删除
                $removedCount++;
            }
            
            return response()->json([
                'status' => 'success',
                'message' => "成功移除 {$removedCount} 个供应商",
                'data' => [
                    'removed_count' => $removedCount,
                    'store_id' => $storeId,
                    'total_requested' => count($vendorIds)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '批量移除失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 生成供应商头像
     *
     * @param string $name
     * @return string
     */
    private function generateVendorAvatar($name)
    {
        $colors = ['#FFC537', '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8'];
        $color = $colors[array_rand($colors)];
        $initials = mb_substr($name, 0, 1, 'UTF-8');
        
        return "data:image/svg+xml;base64," . base64_encode("
            <svg width='40' height='40' viewBox='0 0 40 40' fill='none' xmlns='http://www.w3.org/2000/svg'>
                <circle cx='20' cy='20' r='20' fill='{$color}'/>
                <text x='20' y='25' font-family='Arial, sans-serif' font-size='16' font-weight='bold' text-anchor='middle' fill='white'>{$initials}</text>
            </svg>
        ");
    }

    /**
     * 渲染默认供应商列表（当数据库查询失败时使用）
     *
     * @return string
     */
    private function renderDefaultSupplierList()
    {
        $platforms = [
        ];

        $selectedStoreData = ['id' => 1, 'name' => '默认门店'];
        $suppliers = [];

        return view('admin.supplier.index', compact('platforms', 'selectedStoreData', 'suppliers'));
    }
}